package br.cin.ufpe.corba.namingservice;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Vector;

public class Name implements Serializable {

	private static final long serialVersionUID = -6476721700340726595L;
	
	private Vector<NameComponent> components;
	
	public Name(Vector<NameComponent> components) {
		this.components = components;
	}
	
	public Name(String sname) {
		String[] names = sname.split("/");
		this.components = new Vector<NameComponent>(names.length);
		for (String string : names) {
			this.components.add(new NameComponent(string));
		}
	}

	public Name append(Name name) {
		Vector<NameComponent> result = new Vector<NameComponent>(this.components.size() + name.components.size());
		result.addAll(this.components);
		result.addAll(name.components);
		return new Name(result);
	}
	
	public Name getTail() {
		Vector<NameComponent> childComponents = new Vector<NameComponent>(this.components);
		childComponents.remove(0);
		return new Name(childComponents);
	}
	
	public NameComponent getHead() {
		return this.components.get(0);
	}
	
	public boolean isCompoundName() {
		return this.components.size() > 1;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		
		Iterator<NameComponent> iter = components.iterator();
		while (iter.hasNext()) {
			NameComponent component = iter.next();
			sb.append(component.toString());
			if (iter.hasNext()) {
				sb.append("/");
			}
		}
		
		return sb.toString();
	}
	
}
